<?php
/* TODO:
			*Note* 		'REFRESH' packet code is no longer used in time critical code, only when the bot first connects(04/13/09)
			*Change*	Convert to Associative arrays					- 100%
			*Change*	Multiple kill modifiers(Double Tripple etc., )  - 99%
			*Change*	Server point modifier							- 100%
			*Change*	Check for returns								- 100%
			*Change*	Award points to whole team on a cap				- 100%
*/
require ('pps_player_cache.php');

$team = array( 'score' => 0, 'flag' => 0, 'pc' => 0 );

class base_stats{
	
	var $ps; /* Players */
	var $teams; /* Teams */
	var $pc; /* Player count */
	var $db;
	var $sock;
	var $buffer;
	var $bots;
	private $glbl_team_cap_modifier;
	private $server_tier;
	private $stmt_player;
	private $player_index; /* By name index of players */
    
    /* 'Cache' */
	private $pcache;
    
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function __construct( &$database, &$socket, &$buffer,  $refresh = null ){
/* ---------------------------------------------------------------------------------------------------------------------- */	
		$this->server_tier = 1;
		$this->glbl_team_cap_modifier = round(($this->server_tier * 0.5) , 2);
		
		/* Varriable Refresh array could be used to set stats */
		/* automatically upon creation of the array			  */
		if( isset( $database ) && isset( $socket )  && isset( $buffer ) ){
		
			$this->bots = false;
			$this->db =& $database;
			$this->sock =& $socket;
			$this->buffer =& $buffer;
			
            /* Players */
			$this->pc = 0;
			$this->ps = array();
            /* Player Cache */
            $this->pcache = new player_cache();
            
            /* Teams */
			$this->teams = array();
			$this->teams[0] = $team;
			$this->teams[1] = $team;
				$this->teams[1]['flag'] = 1;
				$this->teams[1]['score'] = $refresh['team'][1];
                $this->teams[1]['FC'] = null;
			$this->teams[2] = $team;
				$this->teams[2]['flag'] = 1;
				$this->teams[2]['score'] = $refresh['team'][2];
                $this->teams[2]['FC'] = null;
	
			$this->stmt_player = $this->db->stmt_init();
			$this->stmt_player->prepare("UPDATE players SET kills=?,deaths=?,doubles=?,triples=?,multi=?,caps=?, 
										grabs=?,returns=?,kd=?,cg=?,ck=?,rating=?,wins=?,maps=?,time_played=?,lastplayed=NOW(),
										`Desert Eagles`=`Desert Eagles`+?,`HK MP5`=`HK MP5`+?,`Ak-74`=`Ak-74`+?,`Steyr AUG`=`Steyr AUG`+?,
										`Spas-12`=`Spas-12`+?,`Ruger 77`=`Ruger 77`+?,`M79`=`M79`+?, `Barrett M82A1`=`Barrett M82A1`+?, 
										`FN Minimi`=`FN Minimi`+?,`XM214 Minigun`=`XM214 Minigun`+?,`Selfkill`=`Selfkill`+?,`Combat Knife`=`Combat Knife`+?,
										`Chainsaw`=`Chainsaw`+?,`LAW`=`LAW`+?,`Grenade`=`Grenade`+?,life_span=?,streak=?,plusminus=?,mu=?,sigma=? WHERE ip=?") or die("COULD NOT PREP");

			$this->stmt_player->execute();
			
			if( isset( $refresh ) ){
				/* WIP */
				if( $refresh['players'] ){
					
					$dublicate = false;
					
					for( $i = 0; $i < $refresh['players']; $i++ ){
					
					
						if( $refresh['player'][$i]['ip'] == "0.0.0.0" )
							if( !$this->bots ) $this->bots = true; else continue;
						
							foreach( $this->ps as $key => $player )
								if( $refresh['player'][$i]['ip'] == $player->ip ) $dublicate = true;
							
							if( $dublicate ) continue;
							
							$data = mysqli_query($database, "SELECT * FROM players WHERE ip=\"" . $refresh['player'][$i]['ip'] . "\"");
						
							$record = mysqli_fetch_array($data);
							if( $record == null ) continue;
						
							$this->ps[$refresh['player'][$i]['name']] = new base_player( $record, $refresh['player'][$i]['name'] ); 
								
							$this->ps[$refresh['player'][$i]['name']]->team = $refresh['player'][$i]['team'];
							
							$this->teams[$this->ps[$refresh['player'][$i]['name']]->team]['pc']++;
							
                            $this->ps[$refresh['player'][$i]['name']]->p_id = $this->pc;
                            
							echo "INIT: <Found Player> ", $this->ps[$refresh['player'][$i]['name']]->name , "(" , $this->ps[$refresh['player'][$i]['name']]->team ,")\n";
							
                            /* Add to the cache */
                            $this->pcache->raise( $refresh['player'][$i]['name'], $record );
                            
							$this->pc++;

					}
				}
			}	
			

			
		
		}
	}
/* ++++ Ranking functions ++++ */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */	
    private function v($val, $e = 0){ /* 'v' function a simple knock off the one shown in TrueSkill(tm) documentation
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        /* This is not even close to the way TrueSkill(tm) and the boys at Microsoft do it
            but it does a pretty good job of coming close and acomplishing what is intended. */
        if( $val > 0 )
            return (pow(1.2, -($val) * 4.5));
        else
            return (pow(1.2, -($val)));
    }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    function w($val, $e = 0){ /* 'w' function knock off */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        if( $val == 0 )
            return 0.999;
        if( $val < 0 )
            return ( 1 / pow(2, -$val * 1.3) );    
        
        return ( 1 / pow(2, $val * 1.3) );
    }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    function c_squared($sigma_w, $sigma_l){ /* Return the value of c squared */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        return 2 + ($sigma_w * $sigma_w) + ($sigma_l * $sigma_l);
    }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    function newSigma($sigma, $c, $Mu_w, $Mu_l){ /* Get the new sigma for a player */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        return sqrt( ($sigma * $sigma) * (1 - ((($sigma*$sigma)/$c) * $this->w( ($Mu_w - $Mu_l)/sqrt($c) )) ) );
    }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    function newMu_w($sigma, $c, $Mu_w, $Mu_l){ /* Get the new Mu for a player(Winner) */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        return $Mu_w + ( (($sigma*$sigma)/sqrt($c)) * $this->v( ($Mu_w - $Mu_l)/sqrt($c) ) );
    }
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    function newMu_l($sigma, $c, $Mu_w, $Mu_l){ /* Get the new Mu for a player(Looser) */
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
        return $Mu_l - ( (($sigma*$sigma)/sqrt($c)) * $this->v( ($Mu_w - $Mu_l)/sqrt($c) ) );
    }
    
    
    
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */	
	private function get_refresh(){
/* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */	
		fputs($this->sock, "REFRESH\r\n");
		while( $this->buffer != "REFRESH" ){
			$this->buffer = trim(fgets($this->sock, 1024));
			if( !$this->buffer ) continue;
			else if($this->buffer == "REFRESH") break;
		}
		
		return GetSoldatInfo($this->sock);
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function ch_join($ip){
/* ---------------------------------------------------------------------------------------------------------------------- */
		$name = substr( $this->buffer , 0 , strpos($this->buffer , "has joined") - 1);
        if( $this->buffer == "$name has joined spectators." ){
            /* Spectators */
            /* Probably better to treat player joining spec as leaving the game alltogether */
            if( array_key_exists($name, $this->ps) )
            {
                $lf = time() - $player->alive_timer;
                if( $lf > $player->alive_time ) $this->ps[$name]->alive_time = $lf;
                if( (time() - $this->ps[$key]->map_timer) > 299 ) $this->ps[$name]->maps++;
                
                $this->update_player_stats($name);
                
                $this->teams[$this->ps[$name]->team]['pc']--;
                
                $p_id = $this->ps[$name]->p_id;
                
                unset($this->ps[$name]);
                ksort($this->ps);
                
				foreach( $this->ps as $key => $player )
                    $this->ps[$key]->dominated[$p_id] = 0;
                    
				$this->pc--;
                return "$name *spec-left*\n";
            }
            
            return false;
        }
        
        /* A player actually joined a team */
        if( $this->buffer == "$name has joined as spectator." ) return false;
		if( !array_key_exists($name, $this->ps) )
		{   /* Add a new player */
            $record = null;
            /* Before querying the database check the cache */
            if( $this->pcache->raise( $name ) ){
                $record = $this->pcache->raise( $name );
            }else{
                $data = mysqli_query($this->db, "SELECT * FROM players WHERE ip=\"". $ip . "\"");
                $record = mysqli_fetch_array($data);
            }
            
			if(!$record ) return false;

			$this->ps[$name] = new base_player( $record, $name );
		}
		else
		{   /* Existing player joined a different team */
			$this->teams[$this->ps[$name]->team]['pc']--;
			$this->pc--;
			$this->ps[$name]->alive_timer = time();
            for($i = 0; $i < 33; $i++ )
                $this->ps[$name]->dominated[$i] = 0;
            
            foreach( $this->ps as $key => $player )
                $this->ps[$key]->dominated[$this->ps[$name]->p_id] = 0;
		}
		if( strpos( $this->buffer, "has joined alpha team.") )
			$this->ps[$name]->team = 1;
		elseif( strpos( $this->buffer, "has joined bravo team.") )
			$this->ps[$name]->team = 2;
		
        
		$this->teams[$this->ps[$name]->team]['pc']++;
		
		$ret = $name . "(" . $this->ps[$name]->team . ")";
		
        $this->ps[$name]->p_id = $this->pc;
        
		$this->pc++;
		
		return $ret;
	}
/* ------------------------------------------------------------------------------------------------------------------- */
	public function ch_left($type)
/* ------------------------------------------------------------------------------------------------------------------- */
	{
		$ret = null;

		foreach( $this->ps as $key => $player )
		{
			$alpha = $player->name;
			$bravo = $player->name;
			$spec = $player->name;
			
			if( $type == 0 ){
				$alpha = $alpha . " has left alpha team.";
				$bravo = $bravo . " has left bravo team.";			
			}elseif( $type == 1 ){
				$loc = strpos($this->buffer, "has been kicked");
				$loc--;
				$name = substr($this->buffer, 0, $loc);
				
				if( !array_key_exists($name, $this->ps) ) return false;
				
				$lf = time() - $player->alive_timer;
				if( $lf > $player->alive_time ) $this->ps[$key]->alive_time = $lf;
				
                if( (time() - $this->ps[$key]->map_timer) > 299 )
                    $this->ps[$key]->maps++;
				
                $this->update_player_stats($name);
				
				$this->teams[$this->ps[$name]->team]['pc']--;
				
                $p_id = $this->ps[$name]->p_id;
                
				unset($this->ps[$name]);
				ksort($this->ps);
                
				foreach( $this->ps as $key => $player )
                    $this->ps[$key]->dominated[$p_id] = 0;
                    
				$this->pc--;
				
				return $name;
			}elseif( $type == 2 ){
				
				$alpha = $player->name . " could not respond";
				$bravo = $player->name . " could not respond";
			}
			
			if( $this->buffer == $alpha || $this->buffer == $bravo || $this->buffer == $spec ){
				$lf = time() - $player->alive_timer;
				if( $lf > $player->alive_time ) $this->ps[$key]->alive_time = $lf;
				
                if( (time() - $this->ps[$key]->map_timer) > 499 )
                    $this->ps[$key]->maps++;
				$this->update_player_stats($key);
				
				$this->teams[$player->team]['pc']--;
				
                $p_id = $this->ps[$key]->p_id;
                
				unset($this->ps[$key]);
				ksort($this->ps);
				//$this->ps = array_values($this->ps);
				foreach( $this->ps as $key => $player )
                    $this->ps[$key]->dominated[$p_id] = 0;
                   
				$this->pc--;
				
				//print_r($this->ps);
                
				return $key;
			}
		}
		
				
		if( $ret ) return $ret; else return false;
	}

/* ---------------------------------------------------------------------------------------------------------------------- */
	/* Returns false on ahem, false positive.. */
	public function ch_kill(/*void*/){
/* ---------------------------------------------------------------------------------------------------------------------- */
		$loc = (strpos($this->buffer, "with")) + 5;
		$weapon = substr($this->buffer, $loc);
		$ret = null;
		$k = null;
		$d = "{unregistered}";
		
		$loc = strpos($this->buffer, "killed (" );

		foreach( $this->ps as $key => $player ){
			if( strpos($this->buffer, $player->name) && strpos($this->buffer, $player->name) < $loc ){
				
				$kill = time();
				
				$speed = ( $this->ps[$key]->kill_count > 1 ) ? 3.02 : 2.02;
				
				$k = $player->name;
				
				if( $kill - $this->ps[$key]->kill_timer < $speed ){
					$this->ps[$key]->kill_count++;
				}else{
					
					//$this->ps[$key]->points += $this->ps[$key]->kill_count * $this->ps[$key]->k_pm;
					$this->ps[$key]->mlt[$this->ps[$key]->kill_count]++;
					$this->ps[$key]->kill_count = 0;
				}
				
				$this->ps[$key]->kill_timer = $kill;
				
				$this->ps[$key]->update_kills($weapon);
		
				break;
			}
		}
		
		foreach( $this->ps as $key => $player ){
			if( strpos($this->buffer, $player->name) > $loc ){
				$this->ps[$key]->d++;
				$d = $this->ps[$key]->name;
				$dt = time() - $this->ps[$key]->alive_timer;
				if( $dt > $this->ps[$key]->alive_time ) $this->ps[$key]->alive_time = $dt;
				$this->ps[$key]->alive_timer = time();
				if( $k ){
                    /* Lets do some dominations... */
                    $this->ps[$k]->dominated[$this->ps[$key]->p_id]++;
                   //fputs($this->sock, "/say " . $this->ps[$k]->dominated[$this->ps[$key]->p_id] . "\r\n");
                    $this->ps[$d]->dominated[$this->ps[$k]->p_id] = 0;
                    if( $this->ps[$k]->dominated[$this->ps[$key]->p_id] > 3 ) 
                    {
                        $killer = $k;
                        $k = $this->ps[$k]->acc_name;
                        $d = $this->ps[$d]->acc_name;
                        
                        switch( $this->ps[$killer]->dominated[$this->ps[$key]->p_id] )
                        {
                            case 4:
                                $domn = "/say $k is harrassing $d...\r\n";
                                fputs($this->sock, $domn);
                                break;
                            case 6:
                                $domn = "/say $k is destroying $d!\r\n";
                                fputs($this->sock, $domn);
                                break;
                            case 8:
                                $domn = "/say $k is DOMINATING $d!!\r\n";
                                fputs($this->sock, $domn);
                                break;
                            case 10:
                                $domn = "/say $k is beating $d like he owes him money..!\r\n";
                                fputs($this->sock, $domn);
                                break;
                            case 20:
                                $domn = "/say Holly shit $k can you leave $d alone?\r\n";
                                fputs($this->sock, $domn);
                                $domn = "/say I mean really, what has $d ever done to deserve this.\r\n";
                                fputs($this->sock, $domn);
                                $domn = "/say Youre going to make him quit this game.....\r\n";
                                fputs($this->sock, $domn);
                                break;
                        }
                        
                    }
				}
				break;
			}
		}
		
		if( !$k ) $k = "{unregistered}";
		if( $k != "{unregistered}" || $d != "{unregistered}" )
		{
			$ret = $k . " kill " . $d . " with " . $weapon;
			return $ret;
		}else{
			return false;
		}
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function ch_grab(/*void*/){
/* ---------------------------------------------------------------------------------------------------------------------- */
		$grab = substr($this->buffer, 0, strpos($this->buffer, "captured the") - 1);
		if( array_key_exists($grab, $this->ps) ){

			$this->ps[$grab]->g++;
			$this->ps[$grab]->points += $this->ps[$grab]->c_pm;
			$this->ps[$grab]->flag = 1;
            /* New code below line(UNTESTED) */
            if( $this->teams[$this->ps[$grab]->team]['FC'] == null )
                $this->teams[$this->ps[$grab]->team]['FC'] = $grab;
            /* Some code to keep track of flags */
			
			$f_team = 0;
			if( $this->ps[$grab]->team == 1 ) $f_team = 2; else $f_team = 1;
			if( !$this->teams[$f_team]['flag'] )
			{
				$this->ps[$grab]->cap_timer = time();
				$this->teams[$f_team]['flag'] = 0;
			}
			return $grab;
		}
		return false;
	}

/* ---------------------------------------------------------------------------------------------------------------------- */
	public function ch_cap(/*void*/){
/* ---------------------------------------------------------------------------------------------------------------------- */
		
		$cap = substr($this->buffer, 0, strpos($this->buffer, "scores for") - 1);
		$ret = null;
		$t = 0;
		$k = 0;
		if( strpos($this->buffer, "scores for Bravo Team") )
        {
			if( array_key_exists($this->teams[2]['FC'], $this->ps ) )
                $cap = $this->teams[2]['FC'];
            $this->teams[2]['score']++;
            $this->teams[2]['FC'] = null;
            $t = 2;
        }
        if( strpos($this->buffer, "scores for Alpha Team") )
        {
			if( array_key_exists($this->teams[1]['FC'], $this->ps ) )
                $cap = $this->teams[1]['FC'];
            $this->teams[1]['score']++;
            $this->teams[1]['FC'] = null;
            $t = 1;
        }

		if( array_key_exists($cap, $this->ps)){
                
            $this->ps[$cap]->c++;
            $this->ps[$cap]->flag = 0;
            $ret = $cap;
            $k = $i;
            
		}
        foreach( $this->ps as $key => $player )
        {
            if( $this->ps[$key]->team == $t )
                $this->ps[$key]->plus_minus++;
            else
                $this->ps[$key]->plus_minus--;
        }
            
		if( $ret ){
			/* Reset the other teams flag */
			$f_team = 0;
			if( $this->ps[$key]->team == 1 ) $f_team = 2; else $f_team = 1;
			$this->teams[$f_team]['flag'] = 1;
            
		}

		if( $ret ) return $ret; else return false;
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function ch_return(/*void*/){
/* ---------------------------------------------------------------------------------------------------------------------- */
		$name = substr($this->buffer, 0, strpos($this->buffer, "returned the") - 1);
		if( array_key_exists($name , $this->ps ))
		{
			$this->ps[$name]->r++;
			$f_team = 0;
			
			/* Set bravo/alpha flag states */
			if( $this->ps[$name]->team == 1 ) $f_team = 2; else $f_team = 1;
			
            $this->teams[$this->ps[$name]->team]['flag'] = 1;
			$this->teams[$f_team]['FC'] = null;
            
			return $name;
		}
		
		return false;
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function ch_nextmap(/*void*/){
/* ---------------------------------------------------------------------------------------------------------------------- */
		$winner = 0;
		if( $this->teams[1]['score'] != $this->teams[2]['score'] )
		{
			if( $this->teams[1]['score'] > $this->teams[2]['score'] )
				$winner = 1;
			else
				$winner = 2;
		}
		/* Update Rankings ( WIP ) */
        if( ( $this->teams[1]['pc'] > 0 ) && ($this->teams[2]['pc'] > 0) )
        {
            /* Okay lets do this ... */
            $Sw = 0; // sigma winner
            $Sl = 0; // sigma looser 
            $Mw = 0; // Mu winner
            $Ml = 0; // Mu looser
            $c = 0; // c squared 
            
            foreach( $this->ps as $key => $player )
            {
                if( $this->ps[$key]->team == 1 || $this->ps[$key]->team == 2 )
                {
                    if( $this->ps[$key]->team == $winner ){
                        $Sw += $this->ps[$key]->sigma;
                        $Mw += $this->ps[$key]->mu;
                    }else{
                        $Sl += $this->ps[$key]->sigma;
                        $Ml += $this->ps[$key]->mu;
                    }
                }
            }
            if( $Sw > 0 && $Sl > 0 ){
            
                $c = $this->c_squared($Sw, $Sl);
                
                foreach( $this->ps as $key => $player )
                {
                    if( $this->ps[$key]->team == $winner )
                    {
                        $this->ps[$key]->mu = $this->newMu_w($Sw, $c, $Mw, $Ml);
                        $this->ps[$key]->sigma = $this->newSigma($Sw, $c, $Mw, $Ml);
                    }else{
                        $this->ps[$key]->mu = $this->newMu_l($Sl, $c, $Mw, $Ml);
                        $this->ps[$key]->sigma = $this->newSigma($Sl, $c, $Mw, $Ml);
                    }
                    $this->ps[$key]->rating = $this->ps[$key]->mu - ( 3 * $this->ps[$key]->sigma );
                }
            }
       }
                

        /* Update maps/wins */
		foreach( $this->ps as $key => $player )
		{
			if( (time() - $this->ps[$key]->map_timer) > 499 )
                $this->ps[$key]->maps++;
            $this->ps[$key]->map_timer = time();
			if($this->ps[$key]->team == $winner ){
				if( $this->ps[$key]->wstreak != 0 )
				{
					if( $this->ps[$key]->wstreak > 0 )
						$this->ps[$key]->wstreak++;
					else
						$this->ps[$key]->wstreak = 1;
				}else{
					$this->ps[$key]->wstreak = 1;
				}
				
				$this->ps[$key]->wins++;
			}else{
				
				if( $this->ps[$key]->wstreak != 0 )
				{
					if( $this->ps[$key]->wstreak > 0 )
						$this->ps[$key]->wstreak = -1;
					else
						$this->ps[$key]->wstreak--;
				}else{
					$this->ps[$key]->wstreak = -1;
				}
			}
            for($i = 0; $i < 32; $i++ )
                $this->ps[$key]->dominated[$i] = 0;
                
			$this->update_player_stats($key);
		}
		
		$this->teams[1]['score'] = 0;
		$this->teams[2]['score'] = 0;
        
        /* Shuffle the players( TODO ) */
        /*$bp = array();
        $b_c = 0;
        $ap = array();
        $a_c = 0;
        $refresh = $this->get_refresh();
        for( $i = 0; $i < $refresh['players']; $i++ )
        {
            if( $refresh['player'][$i]['team'] == 1 ){
                $ab[$a_c] = $refresh['player'][$i]['id'];
                $a_c++;
            }elseif( $refresh['player'][$i]['team'] == 2 ){
                $bp[$b_c] = $refresh['player'][$i]['id'];
                $b_c++;
            }
        }*/
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function update_player_stats($p_num)
/* ---------------------------------------------------------------------------------------------------------------------- */
	{
		/* First Part Update Player specific stats */
		$this->ps[$p_num]->update_kdr();
		$this->ps[$p_num]->update_cgr();
		$this->ps[$p_num]->update_ckr();
		$this->ps[$p_num]->update_time_played();
		
		$this->stmt_player->bind_param('iiiiiiiiddddiiiiiiiiiiiiiiiiiiiiidds', $this->ps[$p_num]->k,
																$this->ps[$p_num]->d,
																$this->ps[$p_num]->mlt[1],
																$this->ps[$p_num]->mlt[2],
																$this->ps[$p_num]->mlt[3],
																$this->ps[$p_num]->c,
																$this->ps[$p_num]->g,
																$this->ps[$p_num]->r,
																$this->ps[$p_num]->kdr,
																$this->ps[$p_num]->cgr,
																$this->ps[$p_num]->ckr,
																$this->ps[$p_num]->rating,
																$this->ps[$p_num]->wins,
																$this->ps[$p_num]->maps,
																$this->ps[$p_num]->tp,
																$this->ps[$p_num]->w['Desert Eagles'], 
																$this->ps[$p_num]->w['HK MP5'], 
																$this->ps[$p_num]->w['Ak-74'],
																$this->ps[$p_num]->w['Steyr AUG'],
																$this->ps[$p_num]->w['Spas-12'],
																$this->ps[$p_num]->w['Ruger 77'],
																$this->ps[$p_num]->w['M79'],
																$this->ps[$p_num]->w['Barrett M82A1'],
																$this->ps[$p_num]->w['FN Minimi'],
																$this->ps[$p_num]->w['XM214 Minigun'],
																$this->ps[$p_num]->w['Selfkill'],
																$this->ps[$p_num]->w['Combat Knife'],
																$this->ps[$p_num]->w['Chainsaw'],
																$this->ps[$p_num]->w['LAW'],
																$this->ps[$p_num]->w['Grenade'],
																$this->ps[$p_num]->alive_time,
																$this->ps[$p_num]->wstreak,
                                                                $this->ps[$p_num]->plus_minus,
                                                                $this->ps[$p_num]->mu,
                                                                $this->ps[$p_num]->sigma,
																$this->ps[$p_num]->ip);
																
		$this->stmt_player->execute() or die("Could Not Execute Prepared Statement\n");
						
		foreach ($this->ps[$p_num]->w as $key => $weapon )
		{
			if( $weapon )
			{
				$query = "UPDATE weapons SET kills=kills+" . $weapon . " WHERE weapon = \"" . $key . "\"";
				mysqli_query($this->db, $query);
			}
			$this->ps[$p_num]->w[$key] = 0;
		}
        
        /* Update the cache */
        $record = array();
        $record['name'] = $this->ps[$p_num]->acc_name;
        $record['kills'] = $this->ps[$p_num]->k;
        $record['deaths'] = $this->ps[$p_num]->d;
        $record['caps'] = $this->ps[$p_num]->c;
        $record['grabs'] = $this->ps[$p_num]->g;
        $record['returns'] = $this->ps[$p_num]->r;
        $record['tier'] = $this->ps[$p_num]->t;
        $record['maps'] = $this->ps[$p_num]->maps;
        $record['wins'] = $this->ps[$p_num]->wins;
        $record['kd'] = $this->ps[$p_num]->kdr;
        $record['cg'] = $this->ps[$p_num]->cgr;
        $record['time_played'] = $this->ps[$p_num]->tp;
        $record['points'] = $this->ps[$p_num]->points;
        $record['ip'] = $this->ps[$p_num]->ip;
        $record['dobules'] = $this->ps[$p_num]->mlt[1];
        $record['triples'] = $this->ps[$p_num]->mlt[2];
        $record['multi'] = $this->ps[$p_num]->mlt[3];
        $record['life_span'] = $this->ps[$p_num]->alive_time;
        $record['streak'] = $this->ps[$p_num]->wstreak;
        $record['plusminus'] = $this->ps[$p_num]->plus_minus;
        $record['mu'] = $this->ps[$p_num]->mu;
        $record['sigma'] = $this->ps[$p_num]->sigma;
        $record['rating'] = $this->ps[$p_num]->rating;
        
        $this->pcache->raise( $p_num, $record );
	}
/* ---------------------------------------------------------------------------------------------------------------------- */
	public function hook_accuracy()
/* ---------------------------------------------------------------------------------------------------------------------- */
	{
		/* WIP */
		/* All of this bellow this line is just pulling information from the encoded line printed by the accuracy soldat script */
		$u_ip = substr($this->buffer, 5, strpos($this->buffer, '[/acc]') - 5 );
		/* Check if the player is actually rated(NOTE: this should not be needed in any code later,
           since only registered players can play in the first place */
        $query = "SELECT * FROM accuracy WHERE ip='$u_ip'";
        $data = mysqli_query($this->db, $query);
		if( !$data ) return;
        $plr = mysqli_fetch_array($data);
        
        /* Uhg this part is a bit ugly but oh well... */
		$info_end = strpos($this->buffer, '[/acc]') + 7;
		$us_dmg = substr($this->buffer, $info_end, strpos($this->buffer, 's',$info_end) - $info_end);
		$info_end += strlen($us_dmg) + 1;
		$us_shots = substr($this->buffer, $info_end, strpos($this->buffer, 'h', $info_end) - $info_end);
		$info_end += strlen($us_shots) + 1;
		$us_hits = substr($this->buffer, $info_end, strpos($this->buffer, 'w', $info_end) - $info_end);
		$info_end += strlen($us_hits) + 4;
		
        
        /* I changed this so that the update code now only uses 2 string arrays, instead of 4(2 strings/2 ints) */
        /* Should save time on typecasting now */
		$us_whit = array(); /* string for hits */
		$us_wshot = array(); /* string for shots */
        $cur_acc = 0;
        
		$us_whit[0] = "0";
		$us_wshot[0] = "0";
            
        /* weapon_number == 0 is Knife, since we dont rate knifes, we start at 1 */
		for( $k = 1; $k < 11; $k++ )
		{
            /* Okay i know this is cumbersome but its better than the old way(**faster**) */
            $l = $k + 1;
            $us_wshot[$k] = substr($this->buffer, $info_end, strpos($this->buffer, ':', $info_end) - $info_end);
			$info_end += strlen($us_wshot[$k]) + 1;
			$us_whit[$k] = substr($this->buffer, $info_end, strpos($this->buffer, "[$l]", $info_end) - $info_end);
			$info_end += strlen($us_whit[$k]) + 3;
            
            if( $us_wshot[$k] != "0" )
            {
                // 1+$k is the start of the weapons: [2]Desert Eagles,[3]Hk[4]Ak ...              
                /* If the player has 0% accuracy just give him w/e he got this game */
                if( $us_whit[$k] != "0" )
                {
                    $cur_acc = round( ($us_whit[$k]/$us_wshot[$k]), 2 );
                    if( $plr[1 + $k] )
                        $plr[1 + $k] = round( ($plr[1+$k] + $cur_acc)/2, 2 );
                    else
                        $plr[1 + $k] = $cur_acc;
                }else
                    $plr[1 + $k] = round( $plr[1 + $k]/2, 2 );   
            }
        }
				
		$query = "UPDATE accuracy SET `Desert Eagles`=". 		$plr[2] . ",".
											"`HK MP5`=". 		$plr[3] . ",".  
											"`Ak-74`=". 		$plr[4] . ",". 
											"`Steyr AUG`=". 	$plr[5] . ",".
											"`Ruger 77`=". 		$plr[7] . ",".
											"`M79`=". 			$plr[8] . ",".
											"`Barrett M82A1`=". $plr[9] . ",".
											"`FN Minimi`=". 	$plr[10] . ",". 
											"`damage`=`damage`+$us_dmg,". 
											"`shots`=`shots`+$us_shots,".
											"`hits`=`hits`+$us_hits". " WHERE `ip`=\"$u_ip\"";
		mysqli_query($this->db, $query);
	
	}
}
